##
##	CSCE 482 CAPSTONE, 2012
##	Texas A&M Univeristy
##	
##	Group Graffiti
##	Members:
##		Matt Shubert 
##		Balazs Makany
##		Eric Gonzalez 
##		Raj Shah
##		Fredy Laksmono
##

try:
	import Queue
	import threading
	import time
	import socket
	import sys
	import zlib
	import binascii
	import ssl
	import commands
	import functions
except ImportError:
	raise
	sys.exit()
except Exception:
	raise
	sys.exit()

### Great appreciation goes to http://www.tutorialspoint.com/python/python_multithreading.htm

try:
	open('server.crt','r')
	open('server.key','r')
	testimage = open('testimage.jpg','r')
except IOError:
	raise
	sys.exit()

#Globals
HOST = ''
PORT = 24888
maxThreads = 1
maxRequest = 10
threadID = 1
exit = 0
threadLock = threading.Lock()
queueLock = threading.Lock()

	
#Thread class
class myThread(threading.Thread):
	def __init__(self, q):
		self.threadID = threadID
		self.q = q
		threading.Thread.__init__(self)
		
	def run(self):
		threadLock.acquire()
		print "Starting thread " + str(self.threadID)
		threadLock.release()
		process(self.threadID, self.q)
		
def process(threadID, q):
	while True:
		queueLock.acquire()
		if not workQueue.empty():
			connection = q.get()
			data = connection.read()
			#decompressed = zlib.decompress(data)
			
			print "\tThread %s processing request %s" % (threadID, data)
			print "\t\t I got  %s" % (data)
			response = commands.command_to_sanitize(data)
			
			#data = data * 2
			print "\t\t I send %s" % (response)
			connection.write(response)
			connection.write(testimage.read())
			
			#to_send = zlib.compress(shit, 9)
			queueLock.release()
			
		else:
			queueLock.release()
			#time.sleep(1)
		
threads = []
requests = []
	
workQueue = Queue.Queue(maxRequest)

#Create Threads
for tName in xrange(maxThreads):
    thread = myThread(workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

#Create Server
try:
	bindsocket = socket.socket()
	bindsocket.bind(('', 24888))
	bindsocket.listen(5)

except socket.error, err:
	print "Can't start server on TCP %d \n%s" % (server_port, err)
	raise SystemExit

#
#MAIN RECEIVER LOOP
#

while True:	
	newsocket, fromaddr = bindsocket.accept()
	connstream = ssl.wrap_socket(newsocket,server_side=True,certfile="server.crt",keyfile="server.key",ssl_version=ssl.PROTOCOL_SSLv23)
	try:
	
			
		#Fill the queue
		queueLock.acquire()
		print "Queue size is %s" % (workQueue.qsize())
		if not workQueue.full():
			workQueue.put(connstream)
		queueLock.release()
	
	
	except:
		print "Unexpected error:", sys.exc_info()[0]
		raise